@extends('layouts.app')

@section('title', '可视化商圈')

@section('css-import')

<!-- <link rel="stylesheet" type="text/css" href="{{config('app.inlet_src')}}/assets/css/htmleaf-demo.css"> -->
<link rel="stylesheet" href="{{config('app.inlet_src')}}assets/css/baguetteBox.min.css">
<!-- <link rel="stylesheet" href="{{config('app.inlet_src')}}/assets/css/gallery-grid.css"> -->
<link rel="stylesheet" href="//api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
<link rel="stylesheet" href="//api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
<style type="text/css">
	 body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
	.identitycardimg_sty{
		width:300px;
		display:block;
	}
	.qrcodeimg{
		cursor:pointer;
	}
	.page-s{
		display: inline-block;
		padding-bottom: 0px;
		margin: 29px 9px;
		border-radius: 4px;
		float:  right;
	}
	#l-map{height:864px;width:100%;margin-top:10px;}
#r-result{width:100%;}
.modal-backdrop{
	z-index: -1 !important;
}
</style>
@endsection

@section('content-fluid')
<div class="row" id="row-data" edit-type="1">
	<form action="/add/circle" method="post" enctype="multipart/form-data" id="confirmeditCircle">
	<div class="col-md-1 pull-right" style="z-index: auto;">
		<button type="button" class="btn btn-primary cleanEdit hhin hide">取消</button>
	</div>
	<div class="col-md-1 pull-right" style="z-index: auto;">
		<button type="button" class="btn btn-primary editCircle editCircleBtn"><i class="fa fa-edit"></i> 修改</button>
	</div>
	<div class="col-md-3 pull-right" style="z-index: auto;">
		<input type="text" name="city" value="" class="form-control form-input-control hhin hide" placeholder="城市名" alt="城市名">
	</div>
	<div class="col-md-3 pull-right" style="z-index: auto;">
		<input type="text" name="name" value="" class="form-control form-input-control hhin hide" placeholder="商圈名称" alt="商圈名称">
	</div>
	<input type="hidden" name="circle_id" value="">
    <input type="hidden" name="position" value="">
    <input type="hidden" name="lng" value="">
	<input type="hidden" name="lat" value="">
	</form>
	<div id="l-map"></div>
</div>
<div class="modal fade" tabindex="-1" id="exampleModal" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">添加商圈</h4>
      </div>
      <form action="/add/circle" method="post" id="addCircleForm">
	      <div class="modal-body">
		  	  <div class="form-group">
	            <label class="control-label">商圈名称</label>
				<input type="text" name="name" value="" class="form-control form-input-control" placeholder="标题名称" alt="标题名称">
				<br>
				<label class="control-label">城市</label>
				<input type="text" name="city" value="" class="form-control form-input-control" placeholder="所在城市" alt="所在城市">
				<br>
	          </div>
	          <input type="hidden" name="circle_id" value="">
	          <input type="hidden" name="position" value="">
	          <input type="hidden" name="lng" value="">
		  	  <input type="hidden" name="lat" value="">
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	        <button type="submit" class="btn btn-primary saveCateImage">保存</button>
	      </div>
      </form>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModalEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="z-index:auto">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">修改商圈</h4>
      </div>
      <!-- <form action="/add/circle" method="post" enctype="multipart/form-data" id="confirmeditCircle"> -->
      <div class="modal-body">
        <table class="table table-hover">
			<thead>
				<tr>
					<th></th>
					<th>商圈名称</th>
				</tr>
			</thead>
			<tbody class="pushlistcircle">
				
			</tbody>
		</table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary select_circle_btn" >选择商圈</button>
      </div>
      <!-- </form> -->
    </div>
  </div>
</div>
<img src="" class="identitycardimg identitycardimg_sty center-block hide">
@endsection

@section('js-import')
<script type="text/javascript" src="{{config('app.inlet_src')}}assets/scripts/baguetteBox.min.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=vQBEj1uCOLD3MPMwoxrICDUhz7vhyR0e"></script>
<!--加载鼠标绘制工具-->
<script type="text/javascript" src="//api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
<!--加载检索信息窗口-->
<script type="text/javascript" src="//api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
@endsection

@section('js-write')
<script type="text/javascript">
	$('.addcircle').click(function(){
		map.clearOverlays();
		var model = $('#exampleModal');
		$('#exampleModal').modal();
	});

	function editcircle(circleid,this_){
		var modal = $('#exampleModalEdit');
		modal.find('input[name="circle_id"]').val(circleid);
		var cname = $(this_).parents('tr').find('.circlename').html();
		var caddress = $(this_).parents('tr').find('.circleaddress').html();
		var lng_lat = $(this_).parents('tr').find('.lng_lat').html().split(",");
		var citycircle = $(this_).parents('tr').find('.citycircle').html();
		var fushe = $(this_).parents('tr').find('.fushe').html();
		modal.find('input[name="name"]').val(cname);
		modal.find('input[name="address"]').val(caddress);
		modal.find('input[name="lng"]').val(lng_lat[0]);
		modal.find('input[name="lat"]').val(lng_lat[1]);
		modal.find('input[name="city"]').val(citycircle);
		modal.find('input[name="circle_range"]').val(fushe);
		if(lng_lat[0] != 0){
			addbj(lng_lat[0],lng_lat[1],fushe);
		}
		modal.modal();
	}

	var editCircleFun = function(){
		$('#exampleModalEdit').modal();
		$('#exampleModalEdit').find('.pushlistcircle').empty();

		$.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
		});
		$.get('/get/circle/all',{},function(response){
			// console.log(response)
			for (var i = response.data.length - 1; i >= 0; i--) {
				var newtr = $('<tr class="circlelist" data_position="'+encodeURI(response.data[i].position)+'" data-lng="'+response.data[i].lng+'" data-lat="'+response.data[i].lat+'" data-city="'+response.data[i].city+'"> <td><input type="radio" name="select_circle" value="'+response.data[i].circle_id+'"></td> <td class="circlename">'+response.data[i].circle_name+'</td> </tr>');
				$('#exampleModalEdit').find('.pushlistcircle').append(newtr);
			}
		});
	}

	$('.editCircleBtn').click(editCircleFun);

	$('.cleanEdit').click(function(){
		$('#confirmeditCircle').find('.hhin').addClass('hide');
		$('#confirmeditCircle').find('.editCircle').attr('type','button');
		$('#confirmeditCircle').find('.editCircle').addClass('editCircleBtn');
		$('#confirmeditCircle').find('.editCircle').html('<i class="fa fa-edit"></i> 修改');
		$('.editCircleBtn').click(editCircleFun);
		$('#row-data').attr('edit-type',"1");
		startOnload();
	});

	$('.select_circle_btn').click(function(){
		$('#exampleModalEdit').modal("hide");
		map.clearOverlays();
		var circle_id = $('input:radio[name="select_circle"]:checked').val();
		var position = $('input:radio[name="select_circle"]:checked').parents('.circlelist').attr('data_position');
		var lng = $('input:radio[name="select_circle"]:checked').parents('.circlelist').attr('data-lng');
		var lat = $('input:radio[name="select_circle"]:checked').parents('.circlelist').attr('data-lat');
		var city = $('input:radio[name="select_circle"]:checked').parents('.circlelist').attr('data-city');
		var circlename = $('input:radio[name="select_circle"]:checked').parents('.circlelist').find('.circlename').html();
		map.centerAndZoom(new BMap.Point(lng,lat),20); 
		$('#confirmeditCircle').find('.hhin').removeClass('hide');
		$('#confirmeditCircle').find('.editCircle').attr('type','submit');
		$('#confirmeditCircle').find('.editCircle').html('保存');
		$('#confirmeditCircle').find('.editCircle').removeClass('editCircleBtn');
		$('#confirmeditCircle').find('.editCircle').unbind('click');
		$('#confirmeditCircle').find('input[name="position"]').val(position);
		$('#confirmeditCircle').find('input[name="lng"]').val(lng);
		$('#confirmeditCircle').find('input[name="lat"]').val(lat);
		$('#confirmeditCircle').find('input[name="name"]').val(circlename);
		$('#confirmeditCircle').find('input[name="city"]').val(city);
		$('#confirmeditCircle').find('input[name="circle_id"]').val(circle_id);
		$('#row-data').attr('edit-type',"0");
		var positions = JSON.parse(decodeURI(position));
		console.log(positions);
		var poss = [];
		for (var i = positions.length - 1; i >= 0; i--) {
			poss.push(new BMap.Point(positions[i].lng,positions[i].lat));
		}
		addPolygon(poss,new BMap.Point(lng,lat),circlename,true);
		// startOnload(true);
	});

	// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	}

	var map = new BMap.Map("l-map");
	map.addControl(new BMap.NavigationControl());
	map.enableScrollWheelZoom(true);
	map.centerAndZoom("石家庄",12); // 初始化地图，设置城市和地图级别。
	var overlays = [];
	var overlaycomplete = function(e){
        overlays.push(e.overlay);
        if($('#row-data').attr('edit-type') == "1"){
        	var model = $('#exampleModal');
        }else{
        	var model = $('#confirmeditCircle');
        }
        if(e.drawingMode === 'marker'){
	        model.find('input[name="lng"]').val(e.overlay.point.lng);
	        model.find('input[name="lat"]').val(e.overlay.point.lat);
	        if($('#row-data').attr('edit-type') == "1"){
				$('#exampleModal').modal();
	        }
        }else if(e.drawingMode === 'polygon' || e.drawingMode === 'polygon'){
	        model.find('input[name="position"]').val(JSON.stringify(e.overlay.zo));
        	toastr.success("绘制完成，请选择商圈中心点");
        }
    };
    var styleOptions = {
        strokeColor:"red",    //边线颜色。
        fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3,       //边线的宽度，以像素为单位。
        strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
        fillOpacity: 0.1,      //填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' //边线的样式，solid或dashed。
    }

    //实例化鼠标绘制工具
    var drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置	
            offset: new BMap.Size(5, 5), //偏离值
        },
        circleOptions: styleOptions, //圆的样式
        polylineOptions: styleOptions, //线的样式
        polygonOptions: styleOptions, //多边形的样式
        rectangleOptions: styleOptions //矩形的样式
    });  
	 //添加鼠标绘制工具监听事件，用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    
    drawingManager.enableCalculate();
    function clearAll() {
		for(var i = 0; i < overlays.length; i++){
            map.removeOverlay(overlays[i]);
        }
        overlays.length = 0
    }
	function addbj(lng_,lat_,fushe,txt){
		// map.clearOverlays();
		var point = new BMap.Point(lng_,lat_);  // 创建点坐标
		map.centerAndZoom(point,18); // 初始化地图,设置城市和地图级别。
		var marker = new BMap.Marker(point)
		marker.enableDragging();
		marker.addEventListener("dragend", function(e){    
		    // alert("当前位置：" + e.point.lng + ", " + e.point.lat); 
		    addbj(e.point.lng,e.point.lat,fushe)
		})
		var circle = new BMap.Circle(point,fushe,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
		// polygon.enableEditing();
		// map.addOverlay(polygon);   //增加多边形
		var opts = {
		  position : point,    // 指定文本标注所在的地理位置
		  offset   : new BMap.Size(10, -30)    //设置文本偏移量
		}
		var label = new BMap.Label(txt, opts);  // 创建文本标注对象
			label.setStyle({
				 color : "red",
				 fontSize : "12px",
				 height : "20px",
				 lineHeight : "20px",
				 fontFamily:"微软雅黑"
			 });
		map.addOverlay(label);
		map.addOverlay(marker);    //添加标注
		map.addOverlay(circle);
	}

	// 绘制多边形
	function addPolygon(position,point,txt,xx){
		if(xx){
			var x = 'dashed';
			// var myIcon = new BMap.Animation("/img/fox.gif", new BMap.Size(300,157));
			var marker = new BMap.Marker(point,{title:txt,enableDragging:true,raiseOnDrag:true}) // 创建标注
			marker.enableDragging();
		}else{
			var x = 'solid';
			var marker = new BMap.Marker(point) // 创建中心点
			var opts = {
			  position : point,    // 指定文本标注所在的地理位置
			  offset   : new BMap.Size(10, -30)    //设置文本偏移量
			}
			var label = new BMap.Label(txt, opts);  // 创建文本标注对象
				label.setStyle({
					 color : "red",
					 fontSize : "12px",
					 height : "20px",
					 lineHeight : "20px",
					 fontFamily:"微软雅黑"
				 });
			map.addOverlay(label);
		}
		var polygon = new BMap.Polygon(position, {strokeColor:"green", strokeWeight:3, strokeOpacity:0.8,strokeStyle:x,fillOpacity:0.1});  //创建多边形
		
		map.addOverlay(polygon);   //增加多边形
		map.addOverlay(marker);   //创建中心点
		marker.setAnimation(BMAP_ANIMATION_DROP)
	}

	var CouponSendParam = {
	    'dataType':'json',
	    'beforeSubmit':CouponBefore,
	    'success':CouponResponse,
	    'error':toutiaoError,
	};
	function CouponBefore(formData, jqForm, options){
	    
	}
	function CouponResponse(response) {
	    if(response.success){
	        setTimeout(function(){
	            location.href = location.href;
	        },2000);
	        toastr.success(response.message);
	    }else{
	        toastr.error('修改失败，请联系开发人员！');
	    }
	}

	function toutiaoError(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==422){
			var RegError = XMLHttpRequest.responseJSON.errors;
			for(var o in RegError){
				for (var i = 0; i < RegError[o].length; i++) {
					toastr.error(RegError[o][i]);
				}
			}
		}
	}
	ajaxForm_('#addCircleForm', CouponSendParam);
	ajaxForm_('#confirmeditCircle', CouponSendParam);
	startOnload();
	function startOnload(editIf){
		map.clearOverlays();
		$.ajaxSetup({
		    headers: {
		        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
		    }
		});
		$.get('/get/circle/all',{},function(response){
			// console.log(response)
			for (var i = response.data.length - 1; i >= 0; i--) {
				// addbj(response.data[i].lng,response.data[i].lat,response.data[i].circle_range,response.data[i].circle_name);
				// console.log(typeof response.data[i].position);
				if(typeof response.data[i].position == 'string' && response.data[i].position != '' && response.data[i].position != null){
					console.log(response.data[i].position);
					var positions = JSON.parse(response.data[i].position);
					var pointpos = [];
					for (var o = positions.length - 1; o >= 0; o--) {
						pointpos.push(new BMap.Point(positions[o].lng,positions[o].lat));
					}
					addPolygon(pointpos,new BMap.Point(response.data[i].lng,response.data[i].lat),response.data[i].circle_name,editIf);
				}else{
					addbj(response.data[i].lng,response.data[i].lat,response.data[i].circle_range,response.data[i].circle_name);
				}
			}

			if (document.createElement('canvas').getContext) {  // 判断当前浏览器是否支持绘制海量点
		        var points = [];  // 添加海量点数据
		        // console.log(response.users)
		        for (var i = 0; i < response.users.length; i++) {
		          points.push(new BMap.Point(response.users[i].last_position_lng, response.users[i].last_position_lat));
		        }
		        var options = {
		            size: BMAP_POINT_SIZE_SMALL,
		            shape: BMAP_POINT_SHAPE_STAR,
		            color: '#d340c3'
		        }
		        var pointCollection = new BMap.PointCollection(points, options);  // 初始化PointCollection
		        pointCollection.addEventListener('click', function (e) {
		        	console.log(e);
		          alert('单击点的坐标为：' + e.point.lng + ',' + e.point.lat);  // 监听点击事件
		        });
		        map.addOverlay(pointCollection);  // 添加Overlay
		    } else {
		        alert('请在chrome、safari、IE8+以上浏览器查看本示例');
		    }
		});
	}
</script>
@endsection